package com.sweetest.luffy.util;


import com.alibaba.fastjson.JSONObject;
import com.sweetest.luffy.vo.PointVo;
import lombok.Data;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GoogleMapUtil {

    public static double getFourPointDistance(PointVo vo) {
        double first = getDistance(vo.getDLatStart(), vo.getDLngStart(), vo.getULatStart(), vo.getULngStart());
        double second = getDistance(vo.getULatStart(), vo.getULngStart(), vo.getULatEnd(), vo.getULngEnd());
        double third = getDistance(vo.getULatEnd(), vo.getULngEnd(), vo.getDLatEnd(), vo.getDLngEnd());
        return first + second + third;
    }

    public static double getTwoPointDistance(PointVo vo) {

        return getDistance(vo.getDLatStart(), vo.getDLngStart(), vo.getDLatEnd(), vo.getDLngEnd());
    }

    private static double getDistance(Double startLat, Double startLng, Double endLat, Double endLng) {
       /* String param = "&origins=" + startLat +
                "|" + startLng + "&destinations=" + endLat +
                "|" + endLng + "&key=AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0";
        String url = "https://maps.googleapis.com/maps/api/distancematrix/json?" + param;
        String str = HttpClientUtil.httpsRequest(url, "GET", null);
        ReturnJson returnJson = JSONObject.parseObject(str, ReturnJson.class);
        return returnJson.getRows().get(0).getDistance().get(0).getValue();*/
        return DistanceUtil.LantitudeLongitudeDist(startLng, startLat, endLng, endLat);
    }
    public static Integer getTwoPointTime(PointVo vo) {

        return getTime(vo.getDLatStart(), vo.getDLngStart(), vo.getDLatEnd(), vo.getDLngEnd());
    }
    private static Integer getTime(Double startLat, Double startLng, Double endLat, Double endLng) {
        String param = "&origins=" + startLat +
                "," + startLng + "&destinations=" + endLat +
                "," + endLng + "&key=AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0";
        String url = "https://maps.googleapis.com/maps/api/directions/json?" + param;
        String str = HttpClientUtil.getHttpsContent(url);
        JSONObject jsonObject = JSONObject.parseObject(str);
        System.out.println(jsonObject);
        Integer time = 0;
        try {
            JSONObject object = jsonObject.getJSONObject("routes").getJSONArray("legs").getJSONObject(0).getJSONObject("duration");
            time = object.getInteger("value");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

    public static void main(String[] args) throws Exception {

//       String str= OkHttpRequestUtils.doGet("https://maps.googleapis.com/maps/api/distancematrix/json?origins=3.1989848613739014,55.8665524481898640&destinations=55.9461719890707060,-3.1879234313964844&key=AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0");
//        String str= OkHttpRequestUtils.doGet("https://www.baidu.com");
//        String str= OkHttpRequestUtils.doGet("https://maps.googleapis.com/maps/api/directions/json?origin=55.923192586088604,-3.17301160099305&destination=55.948890442429324,-3.186437487602234&sensor=false&mode=driving&key=AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0");
//        new OkHttpClient().
//        System.out.println(str);
        httpGet();
//        Map<String, String> postParam = new HashMap<>();
//        postParam.put("origins", "3.1989848613739014|55.8665524481898640");
//        postParam.put("destinations", "55.9461719890707060|-3.1879234313964844");
//        postParam.put("key", "AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0");
//        System.out.println(postUrl("https://maps.googleapis.com/maps/api/distancematrix/json?", postParam));
//        String param = "origins=3.1989848613739014|55.8665524481898640&destinations=55.9461719890707060|-3.1879234313964844&key=AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0";
//        String url = "https://maps.googleapis.com/maps/api/distancematrix/json?" + param;
//        String str = HttpClientUtil.httpsRequest(url, "GET", null);
//        ReturnJson returnJson = JSONObject.parseObject(str, ReturnJson.class);
//        System.out.println(returnJson);
    }

    public static void httpGet() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
//            URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=3.1989848613739014,55.8665524481898640&destinations=55.9461719890707060,-3.1879234313964844&key=AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0");
            // 创建httpget.
            HttpGet httpget = new HttpGet("https://maps.googleapis.com/maps/api/distancematrix/json?origins=3.1989848613739014,55.8665524481898640&destinations=55.9461719890707060,-3.1879234313964844&key=AIzaSyC3hRCtMleheNyr7Dt85gCxbBnhpS6ETB0");
//            httpget.
            httpget.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");
            httpget.addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            httpget.addHeader("content-type", "application/json; charset=UTF-8");
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
//            httpget.addHeader("origins", "3.1989848613739014|55.8665524481898640");

            HttpHost proxy = new HttpHost("74.125.21.98", 80);
            RequestConfig config = RequestConfig.custom()
                    .setProxy(proxy)
                    .build();
            httpget.setConfig(config);
            CloseableHttpResponse response = httpclient.execute(httpget);

            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    System.out.println("Response content: " + EntityUtils.toString(entity));
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Long postUrl(String postUrl, Map<String, String> postParam) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = null;
        Long start = System.currentTimeMillis();
        Long end;
        try {
            //把一个普通参数和文件上传给下面这个地址    是一个servlet
            HttpPost httpPost = new HttpPost(postUrl);
            //设置传输参数
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            //设计文件以外的参数
            Set<String> keySet = postParam.keySet();
            for (String key : keySet) {
                //相当于<input type="text" name="name" value=name>
                multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("text/plain", Consts.UTF_8)));
            }

            HttpEntity reqEntity = multipartEntity.build();
            httpPost.setEntity(reqEntity);

            //发起请求   并返回请求的响应

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                //打印响应状态
                //log.info(response.getStatusLine());
                // resultMap.put("statusCode", response.getStatusLine().getStatusCode());
                //获取响应对象
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    //打印响应内容
                    //resultMap.put("data", EntityUtils.toString(resEntity,Charset.forName("UTF-8")));
                    result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
                    System.out.println(result);
                }
                //销毁
                EntityUtils.consume(resEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            end = System.currentTimeMillis();
        }

        return end - start;
    }

    @Data
    class ReturnJson {
        List<String> destination_addresses;
        List<String> origin_addresses;
        List<Elements> rows;
    }

    @Data
    class Elements {
        List<Distance> distance;
    }

    @Data
    class Distance {
        String text;
        Long value;
    }
    //解析 起点-终点 数据


/*    public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
        try (LocalTestServerContext sc = new LocalTestServerContext("{\"status\" : \"OK\"}")) {
            DistanceMatrixApi.newRequest(sc.context)
                    .origins(new LatLng(-31.9522, 115.8589), new LatLng(-37.8136, 144.9631))
                    .destinations(new LatLng(-25.344677, 131.036692), new LatLng(-13.092297, 132.394057))
                    .awaitIgnoreError();

            try {
                sc.assertParamValue("-31.95220000,115.85890000|-37.81360000,144.96310000", "origins");
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sc.assertParamValue("-25.34467700,131.03669200|-13.09229700,132.39405700", "destinations");
        }
    }*/
}
